<template>
  <div class="page-view-count" v-if="viewCount > 0">
    <span class="view-icon">👁️</span>
    <span class="view-text">{{ viewCount }} 次访问</span>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vitepress'
import { serverAnalyticsService } from '../services/serverAnalytics'
import { getGlobalVersion } from '../composables/useVersion'

const route = useRoute()
const viewCount = ref(0)

// 获取当前页面的访问量
const getPageViewCount = async () => {
  try {
    const currentVersion = getGlobalVersion()
    const stats = await serverAnalyticsService.getStats(currentVersion)
    console.log('stats-----',stats)
    if (stats && stats.popularPages) {
      const currentPath = route.path
      const pageData = stats.popularPages.find(page => page.path === currentPath)
      viewCount.value = pageData ? pageData.views : 0
    }
  } catch (error) {
    console.error('获取页面访问量失败:', error)
    viewCount.value = 0
  }
}

// 监听路由变化
watch(() => route.path, () => {
  getPageViewCount()
})

onMounted(() => {
  getPageViewCount()
})
</script>

<style scoped>
.page-view-count {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  padding: 4px 8px;
  background-color: var(--vp-c-bg-soft);
  border-radius: 6px;
  font-size: 12px;
  color: var(--vp-c-text-2);
  border: 1px solid var(--vp-c-divider);
}

.view-icon {
  font-size: 14px;
}

.view-text {
  font-weight: 500;
}

/* 暗色主题适配 */
.dark .page-view-count {
  background-color: var(--vp-c-bg-soft);
  border-color: var(--vp-c-divider);
  color: var(--vp-c-text-2);
}
</style> 